package com.vancouver.knows.ui.activity.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.common.MyAutoCompleteTextView;
import com.vancouver.knows.util.InputMethodManger;
import com.vancouver.knows.util.PhoConstants;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.task.mark.SearchKeyWordTaskMark;

public class SearchActivity extends BaseActivity implements IResultReceiver {

	private Context mContext;
	@Bind(R.id.search_option_layout)
	RelativeLayout mSearchCancel;
	@Bind(R.id.auto_search)
	MyAutoCompleteTextView mAutoSearch;
	@Bind(R.id.search_layout)
	LinearLayout mLinearLayout;
	@Bind(R.id.clean)
	ImageView mCleanBtn;
	private String mKeyWord;
	private String fromType;

	private InputMethodManger mInputMethodmanager;
	private SearchListView mController;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		mContext = SearchActivity.this;
		setViews();
		setListeners();
	}

	private void setViews() {

		Intent intent = getIntent();
		try {
			fromType = intent.getStringExtra(PhoConstants.FROM_TYPE);
		} catch (Exception e) {
			fromType = null;
		}

		setSearchDefaultHint();
		mInputMethodmanager = new InputMethodManger();
		mSearchCancel.setVisibility(View.VISIBLE);
		mCleanBtn.setVisibility(View.GONE);
		mAutoSearch.requestFocus();
		mAutoSearch.setFocusable(true);
		mAutoSearch.setFocusableInTouchMode(true);

	}

	private void setSearchDefaultHint() {
		String hintText = null;
		if (PhoConstants.FROM_CITY_NEWS.equals(fromType)) {
			hintText = mContext.getString(R.string.search_news_default);
		} else if (PhoConstants.FROM_CITY_DISCOUNT.equals(fromType)) {
			hintText = mContext.getString(R.string.search_discount_default);
		} else if (PhoConstants.FROM_EVENTS.equals(fromType)) {
			hintText = mContext.getString(R.string.search_event_default);
		} else {
			hintText = mContext.getString(R.string.search_default);
		}

		mAutoSearch.setHint(hintText);
	}

	@OnClick(R.id.clean)
	public void onSearchCleanClick() {
		mAutoSearch.setText("");
	}

	private void setListeners() {
		mSearchCancel.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("static-access")
			@Override
			public void onClick(View v) {
				if (mAutoSearch.hasFocus()) {
					mInputMethodmanager.hideKeyboard(mAutoSearch);
				}
				finish();
			}
		});

		mAutoSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				mKeyWord = mAutoSearch.getText().toString().trim();
				if (mKeyWord.length() == 0) {
					mCleanBtn.setVisibility(View.GONE);
				} else {
					mCleanBtn.setVisibility(View.VISIBLE);
				}

				Message message = Message.obtain();
				message.what = PhoConstants.ACTION_USER_SEARCH;
				message.obj = mKeyWord;
				sendDelayMessage(message, 100);
			}
		});

		mAutoSearch.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					if (mAutoSearch.getText().toString().trim().length() > 0) {
						// 有内容时，请求搜索
						mKeyWord = mAutoSearch.getText().toString().trim();
						Message message = Message.obtain();
						message.what = PhoConstants.ACTION_USER_SEARCH;
						message.obj = mKeyWord;
						sendDelayMessage(message, 100);
						return true;
					} else {
						mLinearLayout.removeAllViews();
					}
				}
				return false;
			}
		});
	}

	@Override
	public void subHandleMessage(Message msg) {
		super.subHandleMessage(msg);

		switch (msg.what) {
		case PhoConstants.ACTION_USER_SEARCH:
			searchKeyWord((String) msg.obj);
			break;
		}
	}

	private void searchKeyWord(String keyWord) {
		BusinessModule bModule = imContext.getBusinessModule();
		bModule.getCacheManager().setSearchKeyWorkInfoMap(null);
		SearchKeyWordTaskMark taskMark = bModule.getTaskMarkPool().createSearchKeyWordTaskMarkList();
		if (mController == null) {
			mController = new SearchListView(mContext);
			mController.initLoadableView(keyWord, taskMark, fromType);
			LinearLayout.LayoutParams pm = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);
			mLinearLayout.addView(mController, pm);
		}

		mController.initLoadableView(keyWord, taskMark, fromType);
	}

	@SuppressWarnings("static-access")
	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {

		if (exception != null && !exception.getExMessage().equals("")) {
			mInputMethodmanager.hideKeyboard(mAutoSearch);
			Toast.makeText(mContext, exception.getExMessage(), Toast.LENGTH_LONG).show();
		}
	}

}